package com.sh.secondhand;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.baoyz.widget.PullRefreshLayout;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.sh.Application.BaseApplication;
import com.sh.adapter.MainProductViewFragmentAdapter;
import com.sh.fragment.MainProductViewFrament;
import com.sh.handler.LoginHandler;
import com.sh.secondhand.Login.LoginActivity;
import com.sh.struts.LoginInfo;
import com.sh.utils.Utils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RuntimePermissions
public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    private static Integer REQUEST_CODE_CHOOSE = 1012;
    private static final String TAG = "MainActivity";

    private MainProductViewFragmentAdapter mSectionsPagerAdapter;
    private List<MainProductViewFrament> list;


    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.container)
    ViewPager mViewPager;
    @BindView(R.id.floatingActionButton)
    FloatingActionButton add;
    @BindView(R.id.pull_refresh)
    PullRefreshLayout refreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        /*Drawable drawable=getResources().getDrawable(R.mipmap.search);
        drawable.setBounds(0,0,40,40);
        TextView textView = findViewById(R.id.edt_search);
        textView.setCompoundDrawables(drawable,null,null,null);*/
        setSupportActionBar(toolbar);

        add.setOnClickListener(v -> {
            if(Utils.checkLogin()) {
                MainActivityPermissionsDispatcher.openMatisseWithPermissionCheck(this);
            }else{
                showToastOnThread(MainActivity.this,"请登录再试");
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        DrawerMenuToggle toggle = new DrawerMenuToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        View view = navigationView.getHeaderView(0);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(Utils.checkLogin()) {
                    Intent intent = new Intent(MainActivity.this, UserInfoActivity.class);
                    intent.putExtra("tar_user_id",BaseApplication.getLoginInfo().getUserId());
                    startActivity(intent);
                }else{
                    showToastOnThread(MainActivity.this,"请登录再试");
                }
            }
        });

        list = new ArrayList<>();
        // primary sections of the activity.
        list.add(MainProductViewFrament.newInstance(0, refreshLayout));
        mSectionsPagerAdapter = new MainProductViewFragmentAdapter(getSupportFragmentManager(), list);

        // Set up the ViewPager with the sections adapter.
        mViewPager.setAdapter(mSectionsPagerAdapter);
        new AutoLoginTask().execute((Void) null);
        refreshLayout.setRefreshStyle(PullRefreshLayout.STYLE_MATERIAL);

        refreshLayout.setOnRefreshListener(() -> {
            list.get(0).refreshView();
            refreshLayout.setRefreshing(false);
        });
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        //menu.findItem(R.id.action_change_user).setVisible(false);
        return true;
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if(menu != null) {
            if (Utils.checkLogin()) {
                menu.findItem(R.id.action_login).setVisible(false);
                menu.findItem(R.id.action_logout).setVisible(true);
                menu.findItem(R.id.action_change_user).setVisible(true);
            } else {
                menu.findItem(R.id.action_login).setVisible(true);
                menu.findItem(R.id.action_logout).setVisible(false);
                menu.findItem(R.id.action_change_user).setVisible(false);
            }
        }
        return super.onMenuOpened(featureId, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_login) {
            startActivity(new Intent(MainActivity.this, LoginActivity.class));
            return true;
        } else if (id == R.id.action_change_user) {
            startActivity(new Intent(MainActivity.this, LoginActivity.class));
            return true;
        } else if (id == R.id.action_logout) {
            if (LoginHandler.logout() == true) {
                Toast.makeText(MainActivity.this, "用户已退出登录", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, "操作失败", Toast.LENGTH_SHORT).show();
            }
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_all_order) {
            if (Utils.checkLogin()) {
                Intent intent = new Intent(MainActivity.this, ShowAllOrdersActivity.class);
                startActivity(intent);
            } else {
                showToastOnThread(MainActivity.this, "请登录后再使用此功能");
            }
        } else if (id == R.id.nav_my_collect) {
            if (Utils.checkLogin()) {
                Intent intent = new Intent(MainActivity.this, ShowCollectProductActivity.class);
                startActivity(intent);
            } else {
                showToastOnThread(MainActivity.this, "请登录后再使用此功能");
            }
        } else if (id == R.id.nav_my_fabu) {
            if (Utils.checkLogin()) {
                Intent intent = new Intent(MainActivity.this, MyPublishProductsActivity.class);
                startActivity(intent);
            } else {
                showToastOnThread(MainActivity.this, "请登录后再使用此功能");
            }
        }else if (id == R.id.nav_delivery_address_manage) {
            if (Utils.checkLogin()) {
                Intent intent = new Intent(MainActivity.this, DeliveryAddressManagerActivity.class);
                intent.putExtra("show_pop",false);
                startActivity(intent);
            } else {
                showToastOnThread(MainActivity.this, "请登录后再使用此功能");
            }
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_CHOOSE) {
                List<String> result = Matisse.obtainPathResult(data);
                //创建意图对象
                Intent intent = new Intent(this, PublishProductActivity.class);
                //设置传递键值对
                intent.putExtra("img_path", new Gson().toJson(result));
                //激活意图
                startActivity(intent);
            }
        }
    }

    /**
     * 打开Matisse的图片选择器
     */
    @NeedsPermission({Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
    void openMatisse() {
        Matisse.from(MainActivity.this)
                .choose(MimeType.ofImage()) // 选择 mime 的类型
                .capture(true)  // 开启相机，和 captureStrategy 一并使用否则报错
                .captureStrategy(new CaptureStrategy(true, "com.sh.file.FileProviderImp")) // 拍照的图片路径
                .countable(true)
                .maxSelectable(9) // 图片选择的最多数量
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f) // 缩略图的比例
                .imageEngine(new GlideEngine()) // 使用的图片加载引擎
                .forResult(REQUEST_CODE_CHOOSE); // 设置作为标记的请求码
    }

    @OnPermissionDenied({Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
    void deniedOpenMatisse() {
        Toast.makeText(this, "打开失败，没有对应的权限！", Toast.LENGTH_SHORT).show();
    }

    @OnNeverAskAgain({Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
    void neverAskdeniedOpenMatisse() {
        Toast.makeText(this, "打开失败，请在权限管理中打开对应的权限", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }


    /**
     * 在子线程里需要使用Toast
     *
     * @param context
     * @param message
     */
    public void showToastOnThread(Context context, String message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public class AutoLoginTask extends AsyncTask<Void, Void, Map<String, String>> {

        @Override
        protected Map<String, String> doInBackground(Void... voids) {
            return LoginHandler.autoLogin();
        }

        @Override
        protected void onPostExecute(Map<String, String> stringStringMap) {
            super.onPostExecute(stringStringMap);
            if ("success".equals(stringStringMap.get("status"))) {
                LoginInfo loginInfo = BaseApplication.getLoginInfo();
                if (loginInfo != null) {
                    showToastOnThread(MainActivity.this, "用户 " + loginInfo.getUsername() + " 自动登录成功！");
                    return;
                }
                return;
            }
            showToastOnThread(MainActivity.this, "自动登录失败");
        }
    }

    public void initNavBar(String imgPath, String username) {
        Uri showImgUri = Uri.parse(imgPath);
        SimpleDraweeView simpleDraweeView = findViewById(R.id.nav_image);
        TextView navUsername = findViewById(R.id.nav_username);
        simpleDraweeView.setImageURI(showImgUri);
        navUsername.setText(username);
    }

    private class DrawerMenuToggle extends ActionBarDrawerToggle {

        public DrawerMenuToggle(Activity activity, DrawerLayout drawerLayout, int openDrawerContentDescRes, int closeDrawerContentDescRes) {
            super(activity, drawerLayout, openDrawerContentDescRes, closeDrawerContentDescRes);
        }

        public DrawerMenuToggle(Activity activity, DrawerLayout drawerLayout, Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes) {
            super(activity, drawerLayout, toolbar, openDrawerContentDescRes, closeDrawerContentDescRes);
        }

        /**
         * 当侧滑菜单完全打开时，这个方法被回调
         */
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            LoginInfo loginInfo = BaseApplication.getLoginInfo();
            if (loginInfo != null) {
                initNavBar(loginInfo.getUserImgUrl(), loginInfo.getUsername());
            } else {
                initNavBar("", "未登录");
            }
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    }
}
